/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package university.location;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.SelectItem;
import system.general.Exc;
import system.general.Logged;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "university_locationFind")
@FacesConverter(value = "university_locationFind")
@ViewScoped
public class Find implements Converter {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Beans selectedBean = new Beans();
    private String sql = "";
    private String command = "SELECT us.id, us.id_universidad,us.id_corregimiento,"
            + "c.nombre as nombre_corregimiento, us.direccion,us.nombre,us.geometry ,"
            + " d.id AS id_distrito, d.nombre AS nombre_distrito, "
            + " p.id AS id_provincia, p.nombre AS nombre_provincia, "
            + " pa.id AS id_pais,pa.nombre AS nombre_pais ,"
            + " u.nombre as nombreuniversidad  "
            + " FROM public.v_universidad_sede  us"
            + " INNER JOIN public.v_localizacion_corregimiento c "
            + " ON (us.id_corregimiento=c.id) "
            + "  INNER JOIN public.v_localizacion_distrito d "
            + " ON (c.id_distrito=d.id) "
            + " INNER JOIN public.v_localizacion_provincia p "
            + "ON (d.id_provincia = p.id) "
            + "INNER JOIN public.v_localizacion_pais pa"
            + " ON (p.id_pais=pa.id)"
            + " INNER JOIN public.v_universidad_general u "
            + "  ON (us.id_universidad=u.id)  WHERE ";
    private String order = " ORDER BY nombre ";

    public Find() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    public Beans getSelected() {
        return selectedBean;
    }

    public void setSelected(Beans bean) {
        if (bean != null) {
            logged.setDetailId(bean.getId());
        }
    }

    public List<SelectItem> listItem(String id_universidad) throws Exc, SQLException, Exception {
        Map<String, String> map = new LinkedHashMap<>();
        List<Beans> beansList = new ArrayList<>();

        if (id_universidad == null) {
            return null;
        }
        map.put("us.id_universidad = " + id_universidad, " ");
        beansList = byMap(map);
        if (beansList.isEmpty()) {
            return null;
        }

        ArrayList<SelectItem> itemList = new ArrayList<>();
        for (int i = 0; i < beansList.size(); i++) {
            itemList.add(new SelectItem(beansList.get(i).getId().toString(), beansList.get(i).getNombre()));
        }
        return itemList;
    }

    public List<Beans> getListByLoggedMap() throws Exc, SQLException, Exception {
        if (logged.getMap().isEmpty()) {
            return null;
        }
        return byMap(logged.getMap());
    }

    public List<Beans> getListByLoggedId() throws Exc, SQLException, Exception {
        if (logged.getMasterId() != 0) {
            Map<String, String> map = new LinkedHashMap<>();
            map.put("us.id_universidad = " + logged.getMasterId(), " ");
            return byMap(map);
        }
        return null;
    }

    public boolean byExist(Map map) throws Exc, SQLException, Exception {
        List<Beans> listBean = byMap(map);
        if (listBean.isEmpty()) {
            listBean.clear();
            return false;
        }
        listBean.clear();
        return true;
    }

    public List<Beans> byMap(Map map) throws Exc, SQLException, Exception {
        Iterator it = map.entrySet().iterator();
        StringBuilder criteria = new StringBuilder("");
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();
            criteria.append(e.getKey().toString());
            criteria.append(e.getValue().toString());
        }
        sql = command + criteria + order;
        return executeSql(sql);
    }

    private List<Beans> executeSql(String sql) throws Exc, SQLException, Exception {
        List<Beans> listBean = new ArrayList<>();
        ResultSet rsts = persistencia.executeRsts(sql);
        while (rsts.next()) {
            Beans beans = new Beans(
                    rsts.getInt("id"),
                    rsts.getInt("id_universidad"),
                    rsts.getInt("id_corregimiento"),
                    rsts.getString("nombre_corregimiento"),
                    rsts.getString("nombre"),
                    rsts.getString("direccion"),
                    rsts.getInt("id_distrito"),
                    rsts.getString("nombre_distrito"),
                    rsts.getInt("id_provincia"),
                    rsts.getString("nombre_provincia"),
                    rsts.getInt("id_pais"),
                    rsts.getString("nombre_pais"),
                    rsts.getString("nombreuniversidad"),
                    rsts.getObject("geometry"));
            listBean.add(beans);
        }
        //Desconecta de la base de datos debido a que es un resultset y podria quedar la conexion activa
        persistencia.dbDisconnect();
        return listBean;
    }

    private String strChar(String data) {
        data = data.toLowerCase().trim();
        data = data.replaceAll("á", "a");
        data = data.replaceAll("é", "e");
        data = data.replaceAll("í", "i");
        data = data.replaceAll("ó", "o");
        data = data.replaceAll("ú", "u");
        data = data.replaceAll("a", "[a,á]");
        data = data.replaceAll("e", "[e,é]");
        data = data.replaceAll("i", "[i,í]");
        data = data.replaceAll("o", "[o,ó]");
        data = data.replaceAll("u", "[u,ú]");
        return data;
    }

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("0")) {
            return null;
        }
        return null;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        }
        return String.valueOf(((Beans) value).getId());
    }
}
